package com.fadadianqi.logistics.admin.filter;

import com.fadadianqi.logistics.admin.AdminGlobalConfig;
import com.fadadianqi.logistics.admin.staff.controller.MasterHelper;
import com.fadadianqi.logistics.admin.staff.model.Action;
import com.fadadianqi.logistics.admin.staff.model.Master;
import com.fadadianqi.logistics.admin.staff.service.ActionService;
import com.fadadianqi.logistics.admin.staff.service.MasterService;
import com.yeqiangwei.commons.net.URL;
import com.yeqiangwei.commons.net.URL.Charset;
import com.yeqiangwei.commons.util.HttpServletUtils;
import com.yeqiangwei.commons.util.ParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.yeqiangwei.commons.util.StringHelper.EMPTY;

@Component("filter_adminWebFilter")
public class AdminWebFilter implements Filter {

    protected FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String URI = request.getRequestURI();

        AdminGlobalConfig config = AdminGlobalConfig.build();
        request.setAttribute("adminGlobalConfig", config);

        Master m = MasterHelper.getMaster(request);
        if (m == null) {
            m = masterService.getById(MasterHelper.getId(request));
            MasterHelper.save(request, response, m);
        }
        if (m != null) {
            Map<String, Action> actMap = masterService.findActions(m);
            List<Action> actions = actionService.findAll();
            for (Action a : actions) {
                if (actMap.get(a.getId()) != null) {
                    request.setAttribute(a.getId(), Boolean.TRUE);
                } else {
                    request.setAttribute(a.getId(), Boolean.FALSE);
                }
            }
        }

        setCurrentURLToAttr(request);
        setParamURLToAttr(request);

        uriInspector.setMaster(m);
        Boolean p = uriInspector.hasPermission(URI);
        if (!p) {
            if (m == null) {
                String currentURL = ParamUtils.getRequestURL(request, EMPTY);
                String url = URL.encode(currentURL, Charset.UTF8, EMPTY);
                HttpServletUtils.redirect(response, "/a/login?backURL=" + url);
            } else {
                HttpServletUtils.redirect(response, "/");
            }
        }
        navigation.setPermissionURI(uriInspector.getPermissionURI());
        request.setAttribute("navigation", navigation.toString(URI));
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        filterConfig = null;
    }

    @Autowired
    private URIInspector uriInspector;

    @Autowired
    private MasterService masterService;

    @Autowired
    private ActionService actionService;

    @Autowired
    private Navigation navigation;


    public final String DEFAULT_CURRENT_URL_ENCODE = "CURRENT_URL_ENCODE";
    public final String DEFAULT_CURRENT_URL = "CURRENT_URL";
    public final String DEFAULT_PARAM_URL = "R";

    /**
     * 将当前地址设置到 request attrbute里
     *
     * @param request
     */
    public final void setCurrentURLToAttr(HttpServletRequest request) {
        String currentURL = ParamUtils.getRequestURL(request, EMPTY);
        request.setAttribute(DEFAULT_CURRENT_URL_ENCODE, URL.encode(currentURL, Charset.UTF8, EMPTY));
        request.setAttribute(DEFAULT_CURRENT_URL, currentURL);
    }

    /**
     * &#x4ece;&#x6d4f;&#x89c8;&#x5668;&#x5730;&#x5740;&#x680f;&#x83b7;&#x5f97;&#x8fd4;&#x56de;&#x7684;url&#x5730;&#x5740;&#x540e;&#x8bbe;&#x7f6e;&#x5230;request attrbute&#x91cc;
     *
     * @param request
     */
    public final void setParamURLToAttr(HttpServletRequest request) {
        request.setAttribute(DEFAULT_PARAM_URL
                , ParamUtils.getString(request, DEFAULT_PARAM_URL, EMPTY));
    }
}
